const db = wx.cloud.database();
const app = getApp();
const config = require("../../config.js");
Page({

      /**
       * 页面的初始数据
       */
      data: {
            ids: -1,
            phone: '',
            wxnum: '',
            qqnum: '',
            email: '',
            campus: JSON.parse(config.data).campus,
      },
      choose(e) {
            let that = this;
            that.setData({
                  ids: e.detail.value
            })
            //下面这种办法无法修改页面数据
            /* this.data.ids = e.detail.value;*/
      },
      onLoad() {
            this.getdetail();
      },
      getdetail() {
            let that = this;
            db.collection('user').where({
                  _openid: app.openid
            }).get({
                  success: function (res) {
                        let info = res.data[0];
                        that.setData({
                              phone: info.phone,
                              qqnum: info.qqnum,
                              wxnum: info.wxnum,
                              email: info.email,
                              ids: info.campus.id,
                              _id: info._id
                        })
                  },
                  fail() {
                        wx.showToast({
                              title: '获取失败',
                              icon: 'none'
                        })
                        let e = setTimeout(
                              wx.navigateBack({}), 2000
                        )
                  }
            })
      },
      //获取用户手机号
      getPhoneNumber: function (e) {
            let that = this;
            //判断用户是否授权确认
            if (!e.detail.errMsg || e.detail.errMsg != "getPhoneNumber:ok") {
                  wx.showToast({
                        title: '获取手机号失败',
                        icon: 'none'
                  })
                  return;
            }
            wx.showLoading({
                  title: '获取手机号中...',
            })
            wx.login({
                  success(re) {
                        wx.cloud.callFunction({
                              name: 'regist', // 对应云函数名
                              data: {
                                    $url: "phone", //云函数路由参数
                                    encryptedData: e.detail.encryptedData,
                                    iv: e.detail.iv,
                                    code: re.code
                              },
                              success: res => {
                                    console.log(res);
                                    wx.hideLoading();
                                    if (res.result == null) {
                                          wx.showToast({
                                                title: '获取失败,请重新获取',
                                                icon: 'none',
                                                duration: 2000
                                          })
                                          return false;
                                    }
                                    //获取成功，设置手机号码
                                    that.setData({
                                          phone: res.result.data.phoneNumber
                                    })
                              },
                              fail: err => {
                                    console.error(err);
                                    wx.hideLoading()
                                    wx.showToast({
                                          title: '获取失败,请重新获取',
                                          icon: 'none',
                                          duration: 2000
                                    })
                              }
                        })
                  },
                  fail: err => {
                        console.error(err);
                        wx.hideLoading()
                        wx.showToast({
                              title: '获取失败,请重新获取',
                              icon: 'none',
                              duration: 2000
                        })
                  }
            })
      },
      phInput(e) {
            this.data.phone = e.detail.value;
      },

      emInput(e) {
            this.data.email = e.detail.value;
      },
      // 提交修改
      getUserInfo(e) {
            let that = this;
            console.log(e);
            let test = e.detail.errMsg.indexOf("ok");
            if (test == '-1') {
                  wx.showToast({
                        title: '请授权后方可使用',
                        icon: 'none',
                        duration: 2000
                  });
            } else {
                  that.setData({
                        userInfo: e.detail.userInfo
                  })
                  that.check();
            }
      },
      // 退出登录并删除
      getUserRemove(e) {
            let that = this;
            console.log(e);
            wx.showModal({
                  title: '提示',
                  content: '退出登录的同时还会删除你在本程序数据库的所有信息（不可恢复），保证你的隐私安全。请谨慎！',
                  success(res) {
                        if (res.confirm) {
                              console.log('用户点击确定')
                              db.collection('user').doc(that.data._id).remove({
                                    success: function (res) {
                                          console.log(res.data)
                                          app.userinfo = null;
                                          app.openid = null;
                                    }
                              })
                              // 钱包交易记录删除
                              db.collection('history').where({
                                    _openid: app.openid
                              }).remove({
                                    success: function (res) {

                                    },

                              })
                              // 个人上传的书籍数据库
                              db.collection('books').where({
                                    _openid: app.openid
                              }).remove({
                                    success: function (res) {

                                    },

                              })
                              // 订单记录删除
                              db.collection('order').where({
                                    _openid: app.openid
                              }).remove({
                                    success: function (res) {

                                    },

                              })
                              // 我的发布
                              db.collection('publish').where({
                                    _openid: app.openid
                              }).remove({
                                    success: function (res) {
                                          wx.showToast({
                                                title: '退出成功',
                                                icon: 'success'
                                          });
                                          wx.reLaunch({
                                                url: '/pages/my/my',
                                          })
                                    },

                              })
                        } else if (res.cancel) {
                              console.log('用户点击取消')
                        }
                  }
            })
      },

      //校检
      check() {
            let that = this;
            //校检手机
            let phone = that.data.phone;
            if (phone == '') {
                  wx.showToast({
                        title: '请先获取您的电话',
                        icon: 'none',
                        duration: 2000
                  });
                  return false
            }
            //校检校区
            let ids = that.data.ids;
            let campus = that.data.campus;
            if (ids == -1) {
                  wx.showToast({
                        title: '请先获取您的校区',
                        icon: 'none',
                        duration: 2000
                  });
            }
            //校检邮箱
            let email = that.data.email;
            if (!(/^[a-z0-9]+([._\\-]*[a-z0-9])*@([a-z0-9]+[-a-z0-9]*[a-z0-9]+.){1,63}[a-z0-9]+$/.test(email))) {
                  wx.showToast({
                        title: '请输入常用邮箱并检查是否正确',
                        icon: 'none',
                        duration: 2000
                  });
                  return false;
            }

            wx.showLoading({
                  title: '正在提交',
            })
            db.collection('user').doc(that.data._id).update({
                  data: {
                        phone: that.data.phone,
                        campus: that.data.campus[that.data.ids],
                        email: that.data.email,
                        info: that.data.userInfo,
                        updatedat: new Date().getTime(),
                  },
                  success: function (res) {
                        console.log(res)
                        db.collection('user').doc(that.data._id).get({
                              success: function (res) {
                                    app.userinfo = res.data;
                                    app.openid = res.data._openid;
                                    wx.hideLoading();
                                    wx.showToast({
                                          title: '修改成功',
                                          icon: 'success'
                                    })
                              },
                        })
                  },
                  fail() {
                        wx.hideLoading();
                        wx.showToast({
                              title: '注册失败，请重新提交',
                              icon: 'none',
                        })
                  }
            })
      },
})